import os
import xml.etree.ElementTree as ET

class eww_reader:
    """ Read IAR eww project file, a kind of XML """

    # Handle all child nodes
    def iterate(self, node, ret_dict, prefix = ""):
        for idx in range(len(node)):
            tag = node[idx].tag
            handler = getattr(self, "handler_" + prefix + tag, None)
            if not handler:
                print "No handler for tag: %s" % tag
                continue
            handler(node[idx], ret_dict)


    # Read eww file and parse
    def __init__(self, eww_file):
        if not os.path.isfile(eww_file):
            raise Exception("Invalid file: %s" % eww_file)
        root = ET.parse(eww_file).getroot()

        # Sanity check: tag:workspace
        if not root or root.tag != 'workspace':
            raise Exception("Bad eww file: %s" % eww_file)

        ret_dict = {}
        self.iterate(root, ret_dict)


    # Handlers for project
    def handler_project(self, node, ret_dict):
        proj_dict = {}
        self.iterate(node, proj_dict)
        print proj_dict

    def handler_path(self, node, ret_dict):
        ret_dict["path"] = node.text

    def handler_scc(self, node, ret_dict):
        self.iterate(node, ret_dict)

    def handler_provider(self, node, ret_dict):
        if node.text:
            ret_dict["provider"] = node.text

    def handler_projname(self, node, ret_dict):
        if node.text:
            ret_dict["projname"] = node.text

    def handler_auxprojpath(self, node, ret_dict):
        if node.text:
            ret_dict["auxprojpath"] = node.text


    # Handlers for batchBuild
    def handler_batchBuild(self, node, ret_dict):
        self.iterate(node, ret_dict)

    def handler_batchDefinition(self, node, ret_dict):
        build_dict = {}
        self.iterate(node, build_dict)
        print build_dict

    def handler_name(self, node, ret_dict):
        ret_dict["name"] = node.text

    def handler_member(self, node, ret_dict):
        proj = node.find("project").text
        conf = node.find("configuration").text
        ret_dict[proj] = conf
